package jmine.tec.report.impl.table.pos;

import static jmine.tec.report.impl.table.pos.ReportTablePosRenderer.PARAM_BYTE_SIZE;
import static jmine.tec.report.impl.table.pos.ReportTablePosRenderer.PARAM_POS_CHARSET;
import static jmine.tec.report.impl.table.pos.ReportTablePosRenderer.PARAM_TIMESTAMP_PATTERN;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import jmine.tec.report.api.table.ReportCell;
import jmine.tec.report.impl.table.ReportTableBuilder;

/**
 * @author finx
 * @created Apr 20, 2010
 */
public class TimestampCellPosRenderer implements ReportCellPosRenderer {

    /**
     * {@inheritDoc}
     */
    public void render(OutputStream outputStream, ReportCell cell) throws IOException {
        StringBuilder value = new StringBuilder();
        if (cell.getValue() != null) {
            String timestampPattern = cell.getParameters().getString(PARAM_TIMESTAMP_PATTERN, "dd/MM/yyyy HH:mm:ss");
            SimpleDateFormat dateFormat = new SimpleDateFormat(timestampPattern);
            value.append(dateFormat.format(Date.class.cast(cell.getValue())));
        }
        Long byteSize = cell.getParameters().getLong(PARAM_BYTE_SIZE);
        String charset = cell.getParameters().getString(PARAM_POS_CHARSET);

        while (value.toString().getBytes(charset).length < byteSize) {
            value.append(" ");
        }

        outputStream.write(value.toString().getBytes(charset));
    }

    /**
     * {@inheritDoc}
     */
    public String getRendererType() {
        return ReportTableBuilder.TYPE_TIMESTAMP;
    }

}
